<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Feedback;
use App\Models\User;
use App\Models\Message;
use Illuminate\Http\Request;
use App\Models\Authorization;
use Illuminate\Support\Facades\Redis;
use DB;
use App\Models\Token;
class UserController extends BaseController
{
    CONST DEFAULT_AVATER = 'uploads/images/avatar/default.jpg';
    private $result = array('code' => '10000', 'message' => '系统服务异常', 'data' => array());

    public function __construct()
    {
        Redis::connect(env('REDIS_HOST'));
    }

    /**
     * @api {post} /requestVerifyCode 1. 请求验证码(requestVerifyCode)
     * @apiDescription
     * 请求验证码(requestVerifyCode)。验证码有效期5分钟。
     * @apiGroup user
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {Number{..11}} mobile  手机号码[unique]
     * @apiParam {Number=1, 2} type  请求验证码类型：1 用户注册，2 找回密码
     * @apiHeaderExample {json} Header-Example:
     *      {
     *          "Accept": "application/vnd.argo.v1+json"
     *      }
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *      {
     *          "code": 200,
     *          "message": "验证码发送成功",
     *          "data": []
     *      }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 200 OK
     *     {
     *          "code": 20101,
     *          "message": "手机号码不能为空",
     *          "data": []
     *     }
     */
    public function requestVerifyCode(Request $request)
    {
        // 自定义验证规则
        $rules = [
            'mobile' => 'required|regex:/^1[34578][0-9]{9}$/',
            'type'   => 'required|numeric|in:1,2,3'
        ];
        // 自定义提示
        $messages = [
            'mobile.required' => ['code' => 20101, 'message' => ':attribute 不能为空.', 'data' => []],
            'mobile.regex'    => ['code' => 20102, 'message' => ':attribute 格式不正确.', 'data' => []],
            'type.required'   => ['code' => 20103, 'message' => ':attribute 不能为空.', 'data' => []],
            'type.numeric'    => ['code' => 20104, 'message' => ':attribute 必须是一个数字.', 'data' => []],
            'type.in'         => ['code' => 20106, 'message' => ':attribute 必须是1或者2其中一个.', 'data' => []]
        ];
        $validator = \Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            $messages = $validator->errors()->toArray();
            foreach ($messages as $value) {
                $this->result['code'] = (int)$value[0]['code'];
                $this->result['message'] = $value[0]['message'];
                break;
            }
            return $this->response->array($this->result);
        }

        // 获取手机号码
        $mobile = $request->get('mobile');
        // 获取请求验证码类型
        $type = $request->get('type');

        $flag = $type == 1 ? '[用户注册]' : '[找回密码]';

        // 注册时：判断 mobile 是否已注册
        if ($type == 1) {
            $res = User::where('mobile', $mobile)->first();
            if ($res) {
                $this->result['code'] = 20107;
                $this->result['message'] = '该手机号码已注册';
                return $this->response->array($this->result);
            }
        // 找回密码时：判断 mobile 是否未注册
        } elseif( $type ==2) {
            $res = User::where('mobile', $mobile)->first();
            if (!$res) {
                $this->result['code'] = 20108;
                $this->result['message'] = '该手机号码未注册';
                return $this->response->array($this->result);
            }
        }else{
            $res = User::where('yz_mobile', $mobile)->first();
            if ($res) {
                $this->result['code'] = 20118;
                $this->result['message'] = '该手机号已绑定有赞账号';
                return $this->response->array($this->result);
            }
        }

        // 判断同一IP当前已发送次数
        $todaySmsCount = DB::table('messages')
            ->where('customer_ip', app('request')->ip())
            ->whereBetween('created_at', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')])
            ->count();

        // 判断同一号码当天已发送次数
        $mobileNum = DB::table('messages')
            ->where('to', $mobile)
            ->whereBetween('created_at', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')])
            ->count();

        if ($todaySmsCount > 5 || $mobileNum > 5) {
            $this->result['code'] = 20109;
            $this->result['message'] = '请求次数超过限制!';
            return $this->response->array($this->result);
        }

        $rand_code = randString();
        $smsInfo = array('code' => $rand_code, 'minutes' => 5);
        $key = $type . '_' . $mobile;
        $names = ['type' => $type, 'mobile' => $mobile, 'rand_code' => $smsInfo['code'], 'time' => time()];
        Redis::hMset($key, $names);

        $config = config('tools.sms');
        $response  = $this->sendSms($mobile, $config['templateID'], $params=[$rand_code, $config['validity']]);

        // 验证码和返回内容记录入库
        $attributes = [
            'type'          => $type,
            'to'            => $mobile,
            'temp_id'       => $config['templateID'],
            'data'          => json_encode($smsInfo),
            'result_info'   => $response,
            'sent_time'     => time(),
            'customer_ip'   => $request->getClientIp(),
        ];
        Message::create($attributes);
        // status
        $smsStatus = json_decode($response);

        // 发送成功
        if ((isset($smsStatus->statusCode) && $smsStatus->statusCode == '000000') ||
            (isset($smsStatus->code)       && $smsStatus->code == 0)) {
            $this->result['code'] = 200;
            $this->result['message'] = '验证码发送成功';
            $this->result['data'] = [];
        } else {
            //return $this->response->error(trans('auth.exception'), 400);
            $this->result['code'] = 20105;
            $this->result['message'] = '验证码发送失败，请稍后重试';
        }

        return $this->response->array($this->result);
    }

    /**
     * 调用第三方发送验证码接口
     *
     * @param $mobile
     * @param $template_id
     * @param $params
     * @return bool
     */
    public function sendSms($mobile, $template_id, $params){
        //判断应该使用那个短信接口发送短信，默认第一次使用eolinker接口发送，如果用户申请第二次则使用云片接口进行发送
        $smsType  = $this->getSmsType();
        $smsConfig = config('tools.sms');
        if(1==$smsType){
            $params = json_encode($params);
            $post_data = array (
                'productKey'    => $smsConfig['key'],
                'templateID'    => $template_id,
                'phoneNum'      => $mobile,
                "params"        => $params
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $smsConfig['url']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            // post数据
            curl_setopt($ch, CURLOPT_POST, 1);
            // post的变量
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            $output = curl_exec($ch);
            curl_close($ch);
        }else{
            $post_data = [
                'mobile' =>$mobile,
                'apikey' =>$smsConfig['yun_pian']['key'],
                'text'   =>'【最美食材】您的验证码是'.current($params).'，有效期为'.next($params).'分钟，请尽快验证'
            ];
            $ch = curl_init();
            curl_setopt ($ch, CURLOPT_URL, $smsConfig['yun_pian']['url']);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
            $output = curl_exec($ch);
            curl_close($ch);
        }
        return $output;
    }

    /**
     * 判断使用那个验证码接口发送验证码，第一次发送使用默认第一次使用eolinker接口发送，如果用户申请第二次则使用云片接口进行发送
     * 使用两个方案主要是为了避免一个接口发送验证码失败，另一个接口做为补充发送
     * @return int
     */
    public function getSmsType(){
        $sendCount = Message::where('created_at','>',date('Y-m-d 00:00:00'))->count();
        if(0 == ($sendCount%2)){
            $smsType = 1;
        }else{
            $smsType = 2;
        }
        return $smsType;
    }
    /**
     * @api {post} /users 2. 用户注册(create a user)
     * @apiDescription 创建一个用户(create a user)
     * @apiGroup user
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {Email}  email   email[unique]
     * @apiParam {String} password   password
     * @apiParam {String} name      name
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *         token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL21vYmlsZS5kZWZhcmEuY29tXC9hdXRoXC90b2tlbiIsImlhdCI6IjE0NDU0MjY0MTAiLCJleHAiOiIxNDQ1NjQyNDIxIiwibmJmIjoiMTQ0NTQyNjQyMSIsImp0aSI6Ijk3OTRjMTljYTk1NTdkNDQyYzBiMzk0ZjI2N2QzMTMxIn0.9UPMTxo3_PudxTWldsf4ag0PHq1rK8yO9e5vqdwRZLY
     *     }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 400 Bad Request
     *     {
     *         "email": [
     *             "该邮箱已被他人注册"
     *         ],
     *     }
     */
    public function store(Request $request)
    {
        // 自定义验证规则
        $rules = [
            'mobile'                => 'required|unique:users,mobile,NULL,id,deleted_at,NULL|regex:/^1[34578][0-9]{9}$/',
            'password'              => 'required|min:6|max:20|regex:/^[a-zA-Z0-9~!@#$%^&*()_]{6,20}$/i|confirmed',
            'password_confirmation' => 'required|same:password',
            'code'                  => 'required|string|min:6',
            'platform'              => 'required|numeric|in:1,2',
            'device_type'           => 'required|string|max:50',
            'device_id'             => 'required|string|max:200',
            'system_version'        => 'required|string|max:20'
        ];

        // 自定义提示
        $messages = [
            'mobile.required'                => ['code' => 20201, 'message' => ':attribute 不能为空.', 'data' => []],
            'mobile.unique'                  => ['code' => 20202, 'message' => ':attribute 已经存在.', 'data' => []],
            'mobile.regex'                   => ['code' => 20203, 'message' => ':attribute 格式不正确.', 'data' => []],
            'password.required'              => ['code' => 20204, 'message' => ':attribute 不能为空.', 'data' => []],
            'password.min'                   => ['code' => 20205, 'message' => ':attribute 长度为6到20个字符之间.', 'data' => []],
            'password.max'                   => ['code' => 20205, 'message' => ':attribute 长度为6到20个字符之间.', 'data' => []],
            'password.regex'                 => ['code' => 20206, 'message' => ':attribute 格式不正确.', 'data' => []],
            'password.confirmed'             => ['code' => 20207, 'message' => ':attribute 两次输入不一致.', 'data' => []],
            'password_confirmation.required' => ['code' => 20208, 'message' => '确认密码不能为空.', 'data' => []],
            'password_confirmation.same'     => ['code' => 20209, 'message' => '确认密码和密码必须相同.', 'data' => []],
            'code.required'                  => ['code' => 20210, 'message' => ':attribute 不能为空.', 'data' => []],
            'code.string'                    => ['code' => 20211, 'message' => ':attribute 验证码必须是一个字符串.', 'data' => []],
            'code.min'                       => ['code' => 20212, 'message' => ':attribute 验证码至少为6个字符.', 'data' => []],
            'platform.required'              => ['code' => 20213, 'message' => ':attribute 不能为空.', 'data' => []],
            'platform.numeric'               => ['code' => 20214, 'message' => ':attribute 必须是一个数字.', 'data' => []],
            'platform.in'                    => ['code' => 20214, 'message' => ':attribute 必须是1或者2其中一个.', 'data' => []],
            'device_type.required'           => ['code' => 20215, 'message' => ':attribute 不能为空.', 'data' => []],
            'device_type.string'             => ['code' => 20216, 'message' => ':attribute 必须是一个字符串.', 'data' => []],
            'device_type.max'                => ['code' => 20217, 'message' => ':attribute 不能大于50个字符.', 'data' => []],
            'device_id.required'             => ['code' => 20218, 'message' => ':attribute 不能为空.', 'data' => []],
            'device_id.string'               => ['code' => 20219, 'message' => ':attribute 必须是一个字符串.', 'data' => []],
            'device_id.max'                  => ['code' => 20220, 'message' => ':attribute 不能大于200个字符.', 'data' => []],
            'system_version.required'        => ['code' => 20221, 'message' => ':attribute 不能为空.', 'data' => []],
            'system_version.string'          => ['code' => 20222, 'message' => ':attribute 必须是一个字符串.', 'data' => []],
            'system_version.max'             => ['code' => 20223, 'message' => ':attribute 不能大于20个字符.', 'data' => []]
        ];

        $validator = \Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            $messages = $validator->errors()->toArray();
            foreach ($messages as $value) {
                $this->result['code'] = (int)$value[0]['code'];
                $this->result['message'] = $value[0]['message'];
                break;
            }
            return $this->response->array($this->result);
        }

        $mobile = $request->get('mobile');
        $password = $request->get('password');
        $re_password = $request->get('password_confirmation');
        $code = $request->get('code');

        // 判断 mobile 是否已注册
        $res = User::where('mobile', $mobile)->first();

        if ($res) {
            //return $this->response->errorBadRequest(trans('auth.exist'));
            $this->result['code'] = 20230;
            $this->result['message'] = '该手机号码已注册';
            return $this->response->array($this->result);
        }

        // 从redis中获取手机号对应的验证码
//        $check_code = Redis::get($mobile);
        $check_code = Redis::hGetAll('1_' . $mobile);
        // 判断对应的redis存不存在
        if (empty($check_code)) {
            //return $this->response->errorBadRequest(trans('auth.captcha'));
            $this->result['code'] = 20231;
            $this->result['message'] = '验证码已失效，请重新获取验证码';
            return $this->response->array($this->result);
        }
//        $unix_time = explode('_', $check_code);

        // 判断验证码
        if ($check_code['rand_code'] != $code) {
            //return $this->response->errorBadRequest(trans('auth.captcha'));
            $this->result['code'] = 20232;
            $this->result['message'] = '验证码错误';
            return $this->response->array($this->result);
        }

        // 判断有无过期
        if ($check_code['time'] + 300 < time()) {
            //return $this->response->errorBadRequest(trans('auth.overtime'));
            $this->result['code'] = 20233;
            $this->result['message'] = '验证码超时，请重新获取验证码';
            return $this->response->array($this->result);
        }

        // 判断手机号与验证码符不符合
        if ($mobile . '_' . $code != $check_code['mobile'] . '_' . $check_code['rand_code']) {
            //return $this->response->errorBadRequest(trans('auth.difference'));
            $this->result['code'] = 20234;
            $this->result['message'] = '手机号码与验证码不符';
            return $this->response->array($this->result);
        }

        $attributes = [
            'mobile'        => $mobile,
            'nickname'      => config('tools.user.name'),
            'avatar'        => config('tools.api_url').self::DEFAULT_AVATER,
            'password'      => app('hash')->make($password),
            'code'          => $code,
            'platform'      => $request->get('platform'),
            'device_type'   => $request->get('device_type'),
            'device_id'     => $request->get('device_id'),
            'system_version'=> $request->get('system_version'),
            'client_ip'     => $request->getClientIp(),
            'yz_user_id'    => uniqid(),
            'yz_mobile'     => 0
        ];
        $user = User::create($attributes);

        // 生成token
        $authorization = new Authorization(\Auth::fromUser($user));
        $authorizationArr = $authorization->toArray();

        $token = $authorizationArr['token'];
        $expired_at = $authorizationArr['expired_at'];
        $refresh_expired_at = $authorizationArr['refresh_expired_at'];

        // 更新token信息入库
        $token_attributes = [
            'uid'                   => $user->id,
            'token'                 => $token,
            'expired_at'            => $expired_at,
            'refresh_expired_at'    => $refresh_expired_at,
        ];
        $tokenM = Token::create($token_attributes);

        // 获取用户信息
        $data = User::where('id', $user->id)->select('id', 'mobile', 'nickname', 'gender', 'avatar')->first();
        $this->result['data'] = $data->toArray();

        $this->result['code'] = 200;
        $this->result['message'] = '注册成功';
        $this->result['data']['token_id']   = $tokenM->id;
        $this->result['data']['token']      = $token;
        $this->result['data']['expired_at'] = $expired_at;
        $this->result['data']['refresh_expired_at'] = $refresh_expired_at;

        return $this->response->array($this->result);
    }

    /**
     * @api {post} /uploadAvatar 3. 上传头像(upload user avatar)
     * @apiDescription 上传头像(upload user avatar)
     * 客户端按常规的上传图片处理即可，Content-Disposition: form-data; 头像文件名称：avatar
     * @apiGroup user
     * @apiPermission jwt
     * @apiVersion 0.1.0
     * @apiParam {String} avatar  头像名称
     * @apiHeaderExample {json} Header-Example:
     *     {
     *          "Accept": "application/vnd.argo.v1+json",
     *          "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vdGVzdC5hcGkua291a291bG9vbmcuY29tL2F1dGhvcml6YXRpb25zL2N1cnJlbnQiLCJpYXQiOjE0ODY1MjQzODIsImV4cCI6MTQ4Njc0MjA4MSwibmJmIjoxNDg2NTI2MDgxLCJqdGkiOiJWM2RaTmtWOExTY1BOYVVyIiwic3ViIjoxMn0.b2j4wwNxQ5AZd8hJ1KAgyci3OnOJZgOeisltESHCPtE"
     *     }
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *      {
     *          "code": 200,
     *          "message": "头像上传成功",
     *          "data": {
     *              "id": 10000,
     *              "mobile": "18511891205",
     *              "nickname": "wahaha",
     *              "avatar": "uploads/avatars/10000_1487238303_7008cee7-91e2-4cc9-8585-2aa03ccb461e.jpg"
     *          }
     *      }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 200 OK
     *     {
     *          "code": 20301,
     *          "message": "头像上传失败"
     *          "data": []
     *     }
     */
    public function uploadAvatar(Request $request)
    {
        $user = $this->user();
        // 文件保存路径
        $filepath = 'uploads/avatars';

        // 允许后缀
        $arrowedType = array('jpeg', 'jpg', 'png');

        // 检查文件是否存在
        if ($request->hasFile('avatar')) {
            // 获取头像文件
            $avatar = $request->file('avatar');

            // 判断文件是否上传成功
            if ($avatar->isValid()) {
                // 扩展名
                $ext = $avatar->getClientOriginalExtension();

                if($avatar->getClientSize() > config('tools.avatar_size')){
                    $this->result['code'] = 20306;
                    $this->result['message'] = '图片大小超过2Mb,请重新上传';
                    $this->result['data'] =[];
                    return $this->response->array($this->result);
                }
                if (in_array(strtolower($ext), $arrowedType)) {
                    // 命名文件
                    $newName = $user->id . '_' . time() . '_' . uniqid().'.'.$ext;

                    // 移动文件，并修改名字
                    if ($avatar->move($filepath, $newName)) {
                        // 保存路径
                        $avatarPath = $filepath . '/' . $newName;
                        // 测试
                        // return $avatarPath;

                        // 更新user表中avatar字段
                        User::where('id', $user->id)->update(['avatar' => config('tools.api_url').$avatarPath]);

                        // 返回用户信息
                        //return $this->response->item($user, new UserTransformer());
                        $data = User::where('id', $user->id)->select('id', 'mobile', 'nickname', 'avatar')->first();

                        $this->result['code'] = 200;
                        $this->result['message'] = '图像上传成功';
                        $this->result['data'] = $data->toArray();
                        return $this->response->array($this->result);
                    }
                }else{
                    $this->result['code'] = 20305;
                    $this->result['message'] = '图像格式不正确，请重新上传';
                    return $this->response->array($this->result);
                }
            } else {
                $this->result['code'] = 20301;
                $this->result['message'] = '头像上传失败';
                return $this->response->array($this->result);
            }
        }else{
            $this->result['code'] = 20302;
            $this->result['message'] = '请上传图像';
            return $this->response->array($this->result);
        }
    }

    /**
     * @api {patch} /user 4. 修改个人信息(update my info)
     * @apiDescription 修改个人信息(update my info)
     *
     * 修改那个字段就传递那个字段
     *
     * 注意：PATCH 和 PUT 方法均需设置 Content-Type：application/x-www-form-urlencoded
     * @apiGroup user
     * @apiPermission JWT
     * @apiVersion 0.1.0
     * @apiParam {String{2..4}} [nickname] 昵称
     * @apiHeaderExample {json} Header-Example:
     *     {
     *          "Accept": "application/vnd.argo.v1+json",
     *          "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vdGVzdC5hcGkua291a291bG9vbmcuY29tL2F1dGhvcml6YXRpb25zL2N1cnJlbnQiLCJpYXQiOjE0ODY1MjQzODIsImV4cCI6MTQ4Njc0MjA4MSwibmJmIjoxNDg2NTI2MDgxLCJqdGkiOiJWM2RaTmtWOExTY1BOYVVyIiwic3ViIjoxMn0.b2j4wwNxQ5AZd8hJ1KAgyci3OnOJZgOeisltESHCPtE"
     *     }
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *      {
     *          "code": 200,
     *          "message": "修改成功",
     *          "data": []
     *      }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 200 OK
     *      {
     *          "code": 20403,
     *          "message": "性别必须是一个数字",
     *          "data": []
     *      }
     */
    public function patch(Request $request)
    {
        //自定义验证规则
        $rules = [
            'nickname' => 'string|max:50',
        ];
        //自定义提示
        $messages = [
            'nickname.string'  => ['code' => 20401, 'message' => ':attribute 必须是一个字符串.', 'data' => []],
            'nickname.max'     => ['code' => 20402, 'message' => ':attribute 不能大于50个字符.', 'data' => []],
        ];
        $validator = \Validator::make($request->all(), $rules, $messages);

        //判断是否失败
        if ($validator->fails()) {
            $messages = $validator->errors()->toArray();
            foreach ($messages as $value) {
                $this->result['code'] = (int)$value[0]['code'];
                $this->result['message'] = $value[0]['message'];
                break;
            }
            return $this->response->array($this->result);
        }

        $user = $this->user();
        // 接收参数
        $params = $request->only('nickname');
        $attributes = [];
        // 过滤用户传过来的值
        foreach ($params as $key => $val) {
            if (!is_null($val)) {
                $attributes[$key] = $val;
            }
        }

        if ($attributes) {
            $res = User::where('id', $user->id)->update($attributes);
            if ($res) {
                $this->result['code'] = 200;
                $this->result['message'] = '保存信息成功';
                $this->result['data'] = [];
                return $this->response->array($this->result);
            }
        } else {
            $this->result['code'] = 20409;
            $this->result['message'] = '缺少参数';
            return $this->response->array($this->result);
        }
    }

    /**
     * @api {post} /resetPassword 5. 找回密码(reset password)
     * @apiDescription 找回密码(reset password)
     * @apiGroup user
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {Number{..11}} mobile  手机号码[unique]
     * @apiParam {String{6..20}} password  密码
     * @apiParam {Number{..6}} code  验证码
     * @apiHeaderExample {json} Header-Example:
     *      {
     *          "Accept": "application/vnd.argo.v1+json"
     *      }
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *      {
     *          "code": 200,
     *          "message": "重置密码成功",
     *          "data": []
     *     }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 200 OK
     *     {
     *          "code": 20611,
     *          "message": "验证码错误",
     *          "data": []
     *     }
     */
    public function resetPassword(Request $request)
    {
        // 自定义验证规则
        $rules = [
            'mobile'   => 'required|regex:/^1[34578][0-9]{9}$/',
            'password' => 'required|min:6|max:20|regex:/^[a-zA-Z0-9~!@#$%^&*()_]{6,20}$/i',
            'code'     => 'required|string|min:6'
        ];
        // 自定义提示
        $messages = [
            'mobile.required'   => ['code' => 20601, 'message' => ':attribute 不能为空.', 'data' => []],
            'mobile.regex'      => ['code' => 20602, 'message' => ':attribute 格式不正确.', 'data' => []],
            'password.required' => ['code' => 20603, 'message' => ':attribute 不能为空.', 'data' => []],
            'password.min'      => ['code' => 20604, 'message' => ':attribute 长度为6到20个字符之间.', 'data' => []],
            'password.max'      => ['code' => 20604, 'message' => ':attribute 长度为6到20个字符之间.', 'data' => []],
            'password.regex'    => ['code' => 20605, 'message' => ':attribute 格式不正确.', 'data' => []],
            'code.required'     => ['code' => 20606, 'message' => ':attribute 不能为空.', 'data' => []],
            'code.string'       => ['code' => 20607, 'message' => ':attribute 必须是一个字符串.', 'data' => []],
            'code.min'          => ['code' => 20608, 'message' => ':attribute 长度为6个字符.', 'data' => []]
        ];

        $validator = \Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            $messages = $validator->errors()->toArray();
            foreach ($messages as $value) {
                $this->result['code'] = (int)$value[0]['code'];
                $this->result['message'] = $value[0]['message'];
                break;
            }
            return $this->response->array($this->result);
        }

        $mobile = $request->get('mobile');
        $password = $request->get('password');
        $code = $request->get('code');

        // 获取用户信息
        $user = User::where('mobile', $mobile)->first();

        if (!$user) {
            $this->result['code'] = 20609;
            $this->result['message'] = '该手机号码未注册';
            return $this->response->array($this->result);
        }

        // 从redis中获取手机号对应的验证码
        $check_code = Redis::hGetAll('2_' . $mobile);

        // 判断redis是否存在验证码信息
        if (empty($check_code)) {
            //return $this->response->errorBadRequest(trans('auth.captcha'));
            $this->result['code'] = 20610;
            $this->result['message'] = '验证码已失效，请重新获取验证码';
            return $this->response->array($this->result);
        }

        // 判断验证码
        if ($check_code['rand_code'] != $code) {
            //return $this->response->errorBadRequest(trans('auth.captcha'));
            $this->result['code'] = 20611;
            $this->result['message'] = '验证码错误';
            return $this->response->array($this->result);
        }

        // 判断有无过期
        if ($check_code['time'] + 300 < time()) {
            //return $this->response->errorBadRequest(trans('auth.overtime'));
            $this->result['code'] = 20612;
            $this->result['message'] = '验证码超时，请重新获取验证码';
            return $this->response->array($this->result);
        }

        // 判断手机号与验证码符不符合
        if ($mobile . '_' . $code != $check_code['mobile'] . '_' . $check_code['rand_code']) {
            //return $this->response->errorBadRequest(trans('auth.difference'));
            $this->result['code'] = 20613;
            $this->result['message'] = '手机号码与验证码不符';
            return $this->response->array($this->result);
        }

        // 重置密码
        $password = app('hash')->make($password);
        User::where('id', $user->id)->update(['password' => $password]);

        $this->result['code']    = 200;
        $this->result['message'] = '密码重置成功';
        $this->result['data']    = [];
        return $this->response->array($this->result);
    }

    /**
     * @api {get} /user 6. 当前用户信息(current user info)
     * @apiDescription 当前用户信息(current user info)
     * @apiGroup user
     * @apiPermission JWT
     * @apiVersion 0.1.0
     * @apiHeaderExample {json} Header-Example:
     *     {
     *          "Accept": "application/vnd.argo.v1+json",
     *          "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vdGVzdC5hcGkua291a291bG9vbmcuY29tL2F1dGhvcml6YXRpb25zL2N1cnJlbnQiLCJpYXQiOjE0ODY1MjQzODIsImV4cCI6MTQ4Njc0MjA4MSwibmJmIjoxNDg2NTI2MDgxLCJqdGkiOiJWM2RaTmtWOExTY1BOYVVyIiwic3ViIjoxMn0.b2j4wwNxQ5AZd8hJ1KAgyci3OnOJZgOeisltESHCPtE"
     *     }
     * @apiSuccessExample {json} Success-Response:
     *      HTTP/1.1 200 OK
     *      {
     *          "code": "200",
     *          "message": "获取用户信息成功",
     *          "data": {
     *              "id": 12,
     *              "mobile": "13812345678",
     *              "nickname": "wahaha",
     *              "avatar": "uploads/avatars/12_1486548562751287_b4dd4302-99af-4da6-a7ea-f0163178ba54.jpg"
     *          }
     *      }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 200 OK
     *     {
     *          "code": 20701,
     *          "message": "获取用户信息失败",
     *          "data": []
     *     }
     */
    public function userShow()
    {
        //return $this->response->item($this->user(), new UserTransformer());
        $user = $this->user();

        $data = User::where('id', $user->id)->select('id', 'mobile', 'nickname', 'avatar')->first();

        if ($data) {
            $this->result['code'] = 200;
            $this->result['message'] = '获取用户信息成功';
            $this->result['data'] =$data->toArray() ;
        } else {
            $this->result['code']    = 20701;
            $this->result['message'] = '获取用户信息失败';
            $this->result['data']    = [];
        }

        return $this->response->array($this->result);
    }

    /**
     * 用户反馈
     * @param Request $request
     * @return mixed
     */
    public function userFeedback(Request $request){
        // 自定义验证规则
        $rules = [
            'content'       => 'required|min:10|max:250',
            'contact'       => 'required|min:6|max:100',
        ];
        // 自定义提示
        $messages = [
            'content.required'      => ['code' => 21601, 'message' => ':attribute 不能为空.', 'data' => []],
            'content.min'           => ['code' => 21602, 'message' => ':attribute 长度为10到250个字符之间.', 'data' => []],
            'content.max'           => ['code' => 21603, 'message' => ':attribute 长度为10到250个字符之间.', 'data' => []],
            'contact.min'           => ['code' => 21604, 'message' => ':attribute 长度为6到100个字符之间.', 'data' => []],
            'contact.max'           => ['code' => 21604, 'message' => ':attribute 长度为6到100个字符之间.', 'data' => []],
            'contact.required'      => ['code' => 21605, 'message' => ':attribute 必须输入.', 'data' => []],
        ];
        //对数据进行验证
        $validator = \Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            $messages = $validator->errors()->toArray();
            foreach ($messages as $value) {
                $this->result['code'] = (int)$value[0]['code'];
                $this->result['message'] = $value[0]['message'];
                break;
            }
            return $this->response->array($this->result);
        }

        $content     = $request->get('content');
        $contactInfo = $request->get('contact');
        $feedbackClass = new Feedback();
        $feedbackClass->content = $content;
        $feedbackClass->contact = $contactInfo;
        if($feedbackClass->save()){
            $this->result['code']    = 200;
            $this->result['message'] = '反馈提交成功';
            $this->result['data']    = [] ;
        }else{
            $this->result['code']    = 21610;
            $this->result['message'] = '反馈信息失败，请稍后重试';
        }
        return $this->response->array($this->result);
    }

    public function updateYouZanMobile(){
        $user  = $this->user();
        if(!empty($user->yz_mobile)){
            $this->result['code'] = 21701;
            $this->result['message'] = '您已绑定过有赞账号，请勿重新绑定';
            $this->result['data'] = [];
            return $this->response->array($this->result);
        }
        //更新用户绑定得有赞账号
        $userClass = User::find($user->id);
        $userClass->yz_mobile  = $user->mobile;
        $userClass->save();
        //返回操作结果
        $this->result['code'] = 200;
        $this->result['message'] = '绑定有赞账号成功';
        $this->result['data'] = [];
        return $this->response->array($this->result);
    }

    /**
     * 修改用户密码
     * @param Request $request
     * @return mixed
     */
    public function modifyPassword(Request $request){
        $user  = $this->user();
        // 自定义验证规则
        $rules = [
            'old_password'          => 'required|min:6|max:20',
            'password'              => 'required|min:6|max:20|regex:/^[a-zA-Z0-9~!@#$%^&*()_]{6,20}$/i',
            'password_confirmation' => 'required|same:password'
        ];
        // 自定义提示
        $messages = [
            'old_password.required' => ['code' => 21801, 'message' => ':attribute 不能为空.', 'data' => []],
            'old_password.min'      => ['code' => 21802, 'message' => ':attribute 长度为6到20个字符之间.', 'data' => []],
            'old_password.max'      => ['code' => 21803, 'message' => ':attribute 长度为6到20个字符之间.', 'data' => []],
            'password.min'          => ['code' => 21804, 'message' => ':attribute 长度为6到20个字符之间.', 'data' => []],
            'password.max'          => ['code' => 21804, 'message' => ':attribute 长度为6到20个字符之间.', 'data' => []],
            'password.regex'        => ['code' => 21805, 'message' => ':attribute 格式不正确.', 'data' => []],
            'password_confirmation.required'=> ['code' => 21806, 'message' => ':attribute 不能为空.', 'data' => []],
            'password_confirmation.same' => ['code' => 21807, 'message' => ':attribute 密码不一致.', 'data' => []],
            'password.required'      => ['code' => 21811, 'message' => ':attribute 不能为空.', 'data' => []],
        ];
        //输出验证错误信息
        $validator = \Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            $messages = $validator->errors()->toArray();
            foreach ($messages as $value) {
                $this->result['code'] = (int)$value[0]['code'];
                $this->result['message'] = $value[0]['message'];
                break;
            }
            return $this->response->array($this->result);
        }

        $oldPassword = $request->get('old_password');
        $password    = $request->get('password_confirmation');
        //验证原密码是否正确
        if(!app('hash')->check($oldPassword,$user->password)){
            $this->result['code']    = 21808;
            $this->result['message'] = '原密码输入错误';
            return $this->response()->array($this->result);
        }
        //判断新密码和旧密码不一致
        if($oldPassword == $password){
            $this->result['code']    = 21809;
            $this->result['message'] = '新密码与旧密码一致,请重新输入';
            return $this->response()->array($this->result);
        }
       //更新新用户密码进数据库
        if(User::where('id',$user->id)->update(['password'=>app('hash')->make($password)])){
            $this->result['code']    = 200;
            $this->result['message'] = '密码修改成功';
            return $this->response()->array($this->result);
        }else{
            return $this->response()->array($this->result);
        }
    }

}
